package com.inspur.edp.team.service.impl;

import com.inspur.edp.common.CommonConstants;
import com.inspur.edp.common.CommonUtils;
import com.inspur.edp.common.ParamValidation;
import com.inspur.edp.team.PaasEnvAuthorityService;
import com.inspur.edp.team.PaasTeamMemberService;
import com.inspur.edp.team.PaasTeamService;
import com.inspur.edp.team.dao.PaasEnvAuthorityDao;
import com.inspur.edp.team.dao.PaasTeamMemberDao;
import com.inspur.edp.team.domain.PaasEnvAuthority;
import com.inspur.edp.team.domain.PaasTeamMember;
import com.inspur.edp.team.dto.EnvTeam;
import com.inspur.edp.team.dto.Team;
import com.inspur.edp.team.dto.TeamMember;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.sysmanager.api.data.user.User;
import org.springframework.data.domain.Example;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

public class PaasEnvAuthorityServiceImpl implements PaasEnvAuthorityService {
    private PaasEnvAuthorityDao paasEnvAuthorityDao = SpringBeanUtils.getBean(PaasEnvAuthorityDao.class);
    private PaasTeamMemberDao paasTeamMemberDao = SpringBeanUtils.getBean(PaasTeamMemberDao.class);
    private PaasTeamMemberService paasTeamMemberService = SpringBeanUtils.getBean(PaasTeamMemberService.class);
    private PaasTeamService paasTeamService = SpringBeanUtils.getBean(PaasTeamService.class);
    @Override
    public List<String> getAuthorityMemberlist(String envId, String teamId){
        try {
            // 参数校验
            ParamValidation.checkParam(envId,teamId);
            PaasEnvAuthority paasEnvAuthorityQuery = new PaasEnvAuthority()
                    .setEnvid(envId)
                    .setTeamid(teamId);
            List<PaasEnvAuthority> envauthoritylist = paasEnvAuthorityDao.findAll(Example.of(paasEnvAuthorityQuery));
            List<String> memberIdlist = new ArrayList<>();
            if (!CollectionUtils.isEmpty(envauthoritylist)) {
                for (PaasEnvAuthority paasEnvAuthority : envauthoritylist) {
                    memberIdlist.add(paasEnvAuthority.getMemberid());
                }
            }
            return memberIdlist;
        }catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException("查询所有拥有环境权限的成员信息" , e);
        }
    }

    @Override
    public void addAuthority(String envId, String teamId, String memberId){
        try {
            // 参数校验
            ParamValidation.checkParam(envId,teamId,memberId);
            PaasEnvAuthority paasEnvAuthorityQuery = new PaasEnvAuthority()
                    .setId(UUID.randomUUID().toString())
                    .setEnvid(envId)
                    .setTeamid(teamId)
                    .setMemberid(memberId);
            List<PaasEnvAuthority> envauthoritylist = paasEnvAuthorityDao.findAll(Example.of(paasEnvAuthorityQuery));
            if(!CollectionUtils.isEmpty(envauthoritylist)){
                throw new RuntimeException("该成员已拥有环境权限");
            }else{
                paasEnvAuthorityDao.save(paasEnvAuthorityQuery);
            }

        }catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException("新增成员环境权限发生异常" , e);
        }
    }

    @Override
    public void addTeamAuthority(String envId, String teamId){
        try {
            // 参数校验
            ParamValidation.checkParam(envId,teamId);
            PaasEnvAuthority paasEnvAuthorityQuery = new PaasEnvAuthority()
                    .setEnvid(envId)
                    .setTeamid(teamId);
            List<PaasEnvAuthority> envauthoritylist = paasEnvAuthorityDao.findAll(Example.of(paasEnvAuthorityQuery));
            if(!CollectionUtils.isEmpty(envauthoritylist)){
                throw new RuntimeException("该团队已拥有环境权限");
            }else{
                List<TeamMember> teamMemberlist = paasTeamMemberService.getMemberListByTeamId(teamId);
                for (TeamMember teamMember : teamMemberlist){
                    addAuthority(envId,teamId,teamMember.getId());
                }
            }

        }catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException("新增团队环境权限发生异常" , e);
        }
    }
    @Override
    public void addNewMemberAuthority(List<String> envIdList, String teamId, String userId){
        try {
            ParamValidation.checkParam(teamId,userId);
            PaasTeamMember paasTeamMember = new PaasTeamMember()
                    .setYn(CommonConstants.YN_YES)
                    .setUserId(userId)
                    .setTeamId(teamId);
            Optional<PaasTeamMember> paasTeamMemberOptional = paasTeamMemberDao.findOne(Example.of(paasTeamMember));
            if (!paasTeamMemberOptional.isPresent()) {
                throw new RuntimeException("该名成员已不存在");
            }
            PaasTeamMember paasTeamMemberResult =  paasTeamMemberOptional.get();
            for (String envId :envIdList) {
                addAuthority(envId, teamId, paasTeamMemberResult.getId());
            }
        }catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException("新增成员环境权限发生异常" , e);
        }
    }

    @Override
    public void removeAuthority(String envId, String teamId, String memberId){
        try{
            ParamValidation.checkParam(envId,teamId,memberId);
            PaasEnvAuthority paasEnvAuthorityQuery = new PaasEnvAuthority()
                    .setEnvid(envId)
                    .setTeamid(teamId)
                    .setMemberid(memberId);
            Optional<PaasEnvAuthority> paasEnvAuthority = paasEnvAuthorityDao.findOne(Example.of(paasEnvAuthorityQuery));
            if(!paasEnvAuthority.isPresent()){
                throw new RuntimeException("该成员不拥有环境权限");
            }
            paasEnvAuthorityDao.delete(paasEnvAuthority.get());
        }catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException("移除成员环境权限发生异常", e);
        }
    }

    @Override
    public void removeMemberAuthority(String teamId, String memberId){
        try{
            ParamValidation.checkParam(teamId,memberId);
            PaasEnvAuthority paasEnvAuthorityQuery = new PaasEnvAuthority()
                    .setTeamid(teamId)
                    .setMemberid(memberId);
            List<PaasEnvAuthority> paasEnvAuthoritylist = paasEnvAuthorityDao.findAll(Example.of(paasEnvAuthorityQuery));
            if(!CollectionUtils.isEmpty(paasEnvAuthoritylist)){
                for(PaasEnvAuthority paasEnvAuthority : paasEnvAuthoritylist){
                    paasEnvAuthorityDao.delete(paasEnvAuthority);
                }
            }
        }catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException("移除成员环境权限发生异常", e);
        }
    }

    @Override
    public void removeTeamAuthority(String envId, String teamId){
        try{
            ParamValidation.checkParam(envId,teamId);
            PaasEnvAuthority paasEnvAuthorityQuery = new PaasEnvAuthority()
                    .setTeamid(teamId)
                    .setEnvid(envId);
            List<PaasEnvAuthority> paasEnvAuthoritylist = paasEnvAuthorityDao.findAll(Example.of(paasEnvAuthorityQuery));
            if(!CollectionUtils.isEmpty(paasEnvAuthoritylist)){
                for(PaasEnvAuthority paasEnvAuthority : paasEnvAuthoritylist){
                    paasEnvAuthorityDao.delete(paasEnvAuthority);
                }
            }
        }catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException("移除团队环境权限发生异常", e);
        }
    }

    public List<String> getEnvId(String teamId, String memberId){
        try{
            ParamValidation.checkParam(teamId,memberId);
            List<String> envIdList = new ArrayList<>();
            PaasEnvAuthority paasEnvAuthorityQuery = new PaasEnvAuthority()
                    .setTeamid(teamId)
                    .setMemberid(memberId);
            List<PaasEnvAuthority> paasEnvAuthoritylist = paasEnvAuthorityDao.findAll(Example.of(paasEnvAuthorityQuery));
            if(CollectionUtils.isEmpty(paasEnvAuthoritylist)){
                return envIdList;
            }else{
                for(PaasEnvAuthority paasEnvAuthority : paasEnvAuthoritylist){
                    envIdList.add(paasEnvAuthority.getEnvid());
                }
                return envIdList;
            }
        }catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException("获取环境ID发生异常", e);
        }
    }
    @Override
    public List<EnvTeam> getUserEnvId(String userId){
        try{
            ParamValidation.checkParam(userId);
            List<TeamMember> teamMemberList = paasTeamMemberService.getMemberByUserId(userId);
            List<EnvTeam> envTeamList = new ArrayList<>();
            if (!CollectionUtils.isEmpty(teamMemberList)) {
                for (TeamMember teamMember : teamMemberList){
                    List<String> envIdList = getEnvId(teamMember.getTeamId(),teamMember.getId());
                    Team team = paasTeamService.getTeamByTeamId(teamMember.getTeamId());
                    for (String envId : envIdList){
                        envTeamList.add(new EnvTeam()
                                .setEnvid(envId)
                                .setTeamid(teamMember.getTeamId())
                                .setTeamcode(team.getCode())
                                .setTeamname(team.getName()));
                    }
                }
            }
            return envTeamList;
        }catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new RuntimeException("获取用户拥有的环境权限发生异常", e);
        }
    }

    /**
     * 根据用户ID和团队ID校验用户是否为管理员
     * @param teamId
     */
    @Override
    public boolean editRoleCheck(String teamId){
        User user = CommonUtils.findUserInfo();
        PaasTeamMember paasTeamMemberQuery = new PaasTeamMember()
                .setYn(CommonConstants.YN_YES)
                .setTeamId(teamId)
                .setUserId(user.getId());

        List<PaasTeamMember> result = paasTeamMemberDao.findAll(Example.of(paasTeamMemberQuery));

        for(PaasTeamMember member : result){
            if(!member.getRoleType().equals(CommonConstants.TEAM_ROLE_ADMIN ) && !user.getId().equals("admin")){
                return false;
            }
        }
        return true;
    }
}
